package com.wsoft.core.utils;

import org.apache.commons.lang3.RandomStringUtils;

/**
 * @Author Zhang gukai
 * @Date 2024/12/20 16:39
 */
public class PasswordGenerator {
    private static final String UPPER_CASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String LOWER_CASE_LETTERS = "abcdefghijklmnopqrstuvwxyz";
    private static final String DIGITS = "0123456789";
    private static final String SPECIAL_CHARACTERS = "@#$%^&+=!";

    /**
     * 生成符合高等级密码要求的密码
     *
     * @param length 密码长度
     * @return 生成的密码
     */
    public static String generateHighLevelPassword(int length) {


        // 生成包含大写字母、小写字母、数字和特殊字符的密码
        String password = RandomStringUtils.random(length, UPPER_CASE_LETTERS + LOWER_CASE_LETTERS + DIGITS + SPECIAL_CHARACTERS);

        // 确保密码中包含至少一个大写字母、一个小写字母、一个数字和一个特殊字符
        password = ensurePasswordContainsAllRequiredCharacters(password);

        return password;
    }

    private static String ensurePasswordContainsAllRequiredCharacters(String password) {
        StringBuilder passwordBuilder = new StringBuilder(password);

        // 确保包含至少一个大写字母
        if (!containsCharacter(password, UPPER_CASE_LETTERS)) {
            passwordBuilder.setCharAt(0, getRandomCharacter(UPPER_CASE_LETTERS));
        }

        // 确保包含至少一个小写字母
        if (!containsCharacter(password, LOWER_CASE_LETTERS)) {
            passwordBuilder.setCharAt(1, getRandomCharacter(LOWER_CASE_LETTERS));
        }

        // 确保包含至少一个数字
        if (!containsCharacter(password, DIGITS)) {
            passwordBuilder.setCharAt(2, getRandomCharacter(DIGITS));
        }

        // 确保包含至少一个特殊字符
        if (!containsCharacter(password, SPECIAL_CHARACTERS)) {
            passwordBuilder.setCharAt(3, getRandomCharacter(SPECIAL_CHARACTERS));
        }

        return passwordBuilder.toString();
    }

    private static boolean containsCharacter(String password, String characterSet) {
        for (char c : password.toCharArray()) {
            if (characterSet.indexOf(c) != -1) {
                return true;
            }
        }
        return false;
    }

    private static char getRandomCharacter(String characterSet) {
        int index = (int) (Math.random() * characterSet.length());
        return characterSet.charAt(index);
    }
}
